package com.luoy.threads.semaphore;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

public class TestSemaphore {

	public static void main(String[] args) {
		List<PhoneRoom> rooms = new ArrayList<>();
		rooms.add(new PhoneRoom("Room 1"));
		rooms.add(new PhoneRoom("Room 2"));
		rooms.add(new PhoneRoom("Room 3"));
		rooms.add(new PhoneRoom("Room 4"));
		rooms.add(new PhoneRoom("Room 5"));
		//信号量类，可以认为是多把锁，共享锁
		Semaphore s = new Semaphore(5);
		
		class Task implements Runnable{
			public void run(){
				try {
					//拿到许可证
					s.acquire();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				for(int i = 0 ; i < rooms.size() ; i++){
					PhoneRoom room = rooms.get(i);
					if (room.isFree()){
						room.setFree(false);
						System.out.println(Thread.currentThread().getName()+" entered "+room.getName());
						try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName()+" exited "+room.getName());
						room.setFree(true);
						//释放许可证
						s.release();
						return;
					}
				}
			}
		}
		
		for(int i = 1 ; i <= 10 ; i++){
			Runnable task = new Task();
			Thread t = new Thread(task);
			t.start();
		}
	}

}

class PhoneRoom{
	//原子类，原子操作
	AtomicBoolean isFree = new AtomicBoolean(true);
	String name;

	public PhoneRoom(String name) {
		super();
		this.name = name;
	}

	public boolean isFree() {
		return isFree.get();
	}

	public void setFree(boolean flag) {
		this.isFree.set(flag);
	}
	public String getName(){
		return name;
	}
}